package com.wxzz.elearning.common.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Base64 {
    // 加密
    public static String encode(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
            //据RFC 822规定，每76个字符，还需要加上一个回车换行去掉换行符
            s = s.replaceAll("[\\s*\t\n\r]", "");
        }
        return s;
    }

    // 解密
    public static String decode(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "iot123";
        //System.out.println(s.length());
//        String enStr = encode(s);
//        enStr = "5L2g5aW9IFRoc3Nzc2UgV29yZCE=";
//        String deStr = decode(enStr);
//        System.out.println("原始数据：" + s + "\n加密数据：" + enStr + "\n解密数据：" + deStr);

        Map<String, Object> result = base64Encode(s);
        System.out.println(JSON.toJSONString(result));
        System.out.println(base64Decode(result.get("result") + "", result.get("salt") + ""));
    }


    /**
     * 字符串Base64位加密
     * @param string
     * @return
     */
    public static Map<String, Object> base64Encode(String string) {
        Map<String, Object> data = new HashMap<String, Object>();
        // 生成6位随机数
        //String salt = getSalt();
        //salt = "";
        // 重新封装
        String str = string;// + salt;
        // base64加密
        BASE64Encoder encoder = new BASE64Encoder();
        String result = encoder.encode(str.getBytes());
        data.put("result", result);
        //data.put("salt", salt);
        return data;
    }

    /**
     * 字符串Base64位解密
     * @param str
     * @return
     * @throws IOException
     */
    public static String base64Decode(String str) {
        return base64Decode(str, "");
    }

    /**
     * 字符串Base64位解密
     * @param str
     * @return
     * @throws IOException
     */
    public static String base64Decode(String str, String salt) {
        try {
            if (StrUtil.isNotBlank(str)) {
                BASE64Decoder decoder = new BASE64Decoder();
                String string =  new String(decoder.decodeBuffer(str), "utf-8");;
                String result = string.replaceAll(salt, "");
                return result;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String getSalt() {
        String[] ValidStr = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        int number = ValidStr.length;
        String salt = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            String rand = String.valueOf(ValidStr[random.nextInt(number)]);
            salt += rand;
        }
        return salt;
    }
}